<script setup>
import {ref, reactive, onMounted, getCurrentInstance} from 'vue';

import { useRouter } from 'vue-router';
import { ElMessage  } from 'element-plus'; // 使用 Element Plus 的 message 组件
import { userStore } from '@/store/index.js'
const instance = getCurrentInstance()
const axios = instance.appContext.config.globalProperties.$axios;
const userItemStore = userStore();
const router = useRouter();

const refLoginForm = ref(null); // 创建一个 ref 来引用 el-form

const isButtonDisabled = ref(false);
const codeUrl = ref('');
const loginForm = reactive({
  account: '',
  password: '',
  code: '1234',
  key: '',
});

const rules = reactive({
  account: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 4, message: '长度必须是4位', trigger: 'blur' }
  ]
});

const userLogin = () => {
  // 发起登录请求
  refLoginForm.value.validate(valid => {
    if (valid) {
      axios.post('/user/login', loginForm).then(resp => {
        const user = resp.data;
        // 这里响应头大小写敏感，要写成小写
        localStorage.setItem('token', resp.headers.authorization);
        // 保存用户信息，转成字符串保存
        localStorage.setItem('user', JSON.stringify(user));

        //存储用户
        userItemStore.updateUser(user)
        console.log(user)
        //修改状态
        userItemStore.updateLoginStatus(true)
        console.log(true)
        // 提示登录成功
        ElMessage({
          message:`登录成功，欢迎您：${user.account}！`,
          type:'success'
        });
        // 跳转到首页
        router.push('/');
      }).catch(error => {
        // 登录失败
        const messageText = error.response.data;
        ElMessage.error(`登录失败，${messageText}`);
      });
    } else {
      return false;
    }
    isButtonDisabled.value = true
    setTimeout(() => {
      isButtonDisabled.value = false;
    }, 5000);
  });
}

const getCaptcha = ()=>{
  axios.get('/user/code').then(resp => {
    //返回两个数据：key是Redis中key，base64Img是图片
    codeUrl.value = resp.data.base64Img;
    loginForm.key = resp.data.key;
  })
}

onMounted(()=>{
  getCaptcha()
})
</script>

<template>
  <div class="login-container">
    <el-tabs v-model="activeName" type="border-card">
      <el-tab-pane label="用户名登录" name="userName">
        <el-card class="card">
          <h2 class="title">蜗牛书城用户登录</h2>
          <el-form ref="refLoginForm"
                   :model="loginForm" class="login-form" :rules="rules" label-position="left"
                   label-width="80px">
            <el-form-item label="用户名：" prop="account">
              <el-input v-model="loginForm.account"
                        placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item label="密码：" prop="password">
              <el-input type="password" v-model="loginForm.password"
                        placeholder="请输入密码"></el-input>
            </el-form-item>
            <el-form-item label="验证码：" prop="code">
              <div class="form-item-container">
                <el-input v-model="loginForm.code" maxlength="4"
                          minlength="4" placeholder="验证码"
                          style="width: 90px;">
                </el-input>
                <img :src="codeUrl"
                     style="cursor: pointer; margin-left: 10px;"
                     @click="getCaptcha()"
                     title="看不清点击刷新"/>
              </div>
            </el-form-item>
            <div class="login-btn-container">
              <el-button style="width: 150px;" type="primary"
                         @click="userLogin"
                         :disabled="isButtonDisabled"
                         icon="el-icon-user-solid">登录
              </el-button>
            </div>
          </el-form>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<style scoped>
.login-container {
  position: fixed;
  height: 100%;
  width: 100%;
  left: 0;
  background-image: linear-gradient(0, rgb(68, 68, 235), lightblue);
  display: flex;
  /* 水平居中对齐 */
  justify-content: center;
  /* 垂直居中对齐 */
  height: 100%;
}

.container{
  width: 380px;
}
.card {
  margin-top: 20px;
  width: 450px;
  height: 430px;
  padding: 15px;
}

.title {
  margin-top: 10px;
  font-size: 25px;
  text-shadow: 2px 2px 4px #888;
  text-align: center;
}

.login-form {
  max-width: 300px;
  margin: 0 auto;
}

.login-btn-container {
  text-align: center;
  margin-bottom: 30px;
}

.form-item-container {
  display: flex;
  align-items: flex-end;
}
</style>